﻿CREATE PROCEDURE [dbo].[RepearPassword_CreateRestoreHash]
	@email nvarchar(256)
AS
BEGIN
	SET @email = LOWER(@email)
	DECLARE @userHashCode NVARCHAR(32)

	IF NOT EXISTS( SELECT * FROM [dbo].[user_User] WHERE [Email] = @email)
	BEGIN
		RAISERROR ('EmailNotExist',9,1)
		RETURN
	END

	SELECT @userHashCode = [HashCode] FROM [dbo].[user_User] WHERE [Email] = @email

	DECLARE @restoreHashCode nvarchar(32)

	SET @restoreHashCode = CAST([dbo].[RandString](32) AS NVARCHAR(32))
	WHILE EXISTS (SELECT * FROM [dbo].[user_Restore] WHERE [RestoreHashCode] = @restoreHashCode)
	BEGIN
		SET @restoreHashCode = CAST([dbo].[RandString](32) AS NVARCHAR(32))
	END


	INSERT INTO [dbo].[user_Restore] ([Email], [UserHashCode], [RestoreHashCode])
	VALUES (@email, @userHashCode, @restoreHashCode)

	SELECT @restoreHashCode AS 'RestoreHashCode'

END